import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:number_pagination/number_pagination.dart';
import 'package:wallpaper_app/api/wallpaper360.dart';
import 'package:wallpaper_app/components/Images/image_list_base.dart';
import 'package:wallpaper_app/model/image_base.dart';

class ImageListNew360 extends StatefulWidget {
  const ImageListNew360({super.key});

  @override
  State<ImageListNew360> createState() => _ImageList360State();
}

class _ImageList360State extends State<ImageListNew360> {
  List<ImageBase> imgs = [];
  bool isLoading = false;
  int pageno = 1;
  int count = 30;
  int totalPage = 1;

  Future<void> getData() async {
    if (!mounted) return;
    setState(() {
      isLoading = true;
      imgs.clear();
    });
    try {
      Response res = await get360NewWallpaper(
        pageno: pageno,
        count: count,
      );
      if (res.statusCode == 200) {
        List<dynamic> list = res.data['data']['list'];
        setState(() {
          totalPage = res.data['data']['total_page'];
        });
        imgs = list
            .map(
              (e) => ImageBase(
                largePath: e['url'],
                smallPath: e['url'],
                tags: e['tag'].replaceAll(',', ' '),
              ),
            )
            .toList();
      }
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context).colorScheme;
    return Scaffold(
      body: Stack(
        children: [
          ImageListBase(imageList: imgs, isLoading: isLoading),
          Positioned(
            bottom: 10,
            left: 0,
            right: 0,
            child: NumberPagination(
              onPageChanged: (int pageNumber) {
                setState(() {
                  pageno = pageNumber;
                });
                getData();
              },
              visiblePagesCount: 10,
              totalPages: totalPage,
              currentPage: pageno,
              buttonRadius: 5,
              controlButtonSize: Size(28, 28),
              numberButtonSize: Size(28, 28),
              selectedButtonColor: theme.primary,
            ),
          )
        ],
      ),
    );
  }
}
